from django.shortcuts import render
from django.http import HttpResponse, JsonResponse
import random
from Register.models import *
from django.core.urlresolvers import reverse
from django.shortcuts import redirect


# Create your views here.
def delete(request):
    s = Student.objects.filter(name="zyd20011204")
    # email = s.email
    # e = Email.objects.filter(email_addr="178320369@qq.com")
    s.delete()
    # e.delete()
    return HttpResponse("删除成功!!")


def check_user(request):
    username = request.POST.get("username")
    student = Student.objects.filter(name=username)
    status = request.POST.get("status")
    if student:
        return JsonResponse({"status_num": 1, "msg": "账号已经存在!!"})
    else:
        return JsonResponse({"status_num": 0, "msg": "账号不存在"})


def check_email(request):
    email = request.POST.get("email")
    email_addr = Email.objects.filter(email_addr=email)

    if email_addr:
        print({"status_num": 1, "msg": "邮箱已经绑定"})
        return JsonResponse({"status_num": 1, "msg": "邮箱已经绑定"})
    else:
        return JsonResponse({"status_num": 0, "msg": "邮箱未绑定"})


def send_code(request):
    # 制作验证码
    code = ""
    for i in range(5):
        s1 = str(random.randint(1, 9))
        code += s1
    from django.core.mail import send_mail, send_mass_mail
    from online_school.settings import EMAIL_FROM
    rec_li = [request.POST.get("email")]
    # res = "您本次注册的验证码为" + code + "请勿转告他人!"
    res = "鉴于您最近14天去过中高风险区，您已被禁止前往峡谷，请居家隔离，配合检疫工作！(手动滑稽)"
    try:
        for obj in rec_li:
            ms1 = ("德玛西亚防疫部门", res, EMAIL_FROM, [obj])
            send_mass_mail((ms1,), )
            print("验证码发送成功!!")
        return JsonResponse({"code_num": code})
    except Exception as e:
        return HttpResponse(e)  # 如果发送邮件异常，返回错误信息。


def send_massage(username, email):
    from django.core.mail import send_mail, send_mass_mail
    from online_school.settings import EMAIL_FROM
    rec_li = [email]
    res = "召唤师:%s" \
          "恭喜您已经成功注册账号!!" % username
    try:
        for obj in rec_li:
            ms1 = ("德玛西亚政府", res, EMAIL_FROM, [obj])
            send_mass_mail((ms1,), )
            print("发送信息成功!!")
        return True
    except Exception:
        return False  # 如果发送邮件异常，返回错误信息。
